package flexcommon.validators
{
	import flexcommon.utils.StringUtils;
	import flexcommon.validators.support.RoutingCountryDefinition;
	import flexcommon.validators.support.RoutingNumberRules;
	
	import mx.validators.ValidationResult;
	import mx.validators.Validator;

	/**
   * Validates the routing number length based on the country specified.
   * 
   * <p>
   * Currently this validator works for three country codes: CA, US and GB.
   * </p>
   * 
   * @author Dimitrios Gianninas
   * 
   * @see RoutingNumberRules
   */
	public class RoutingNumberValidator extends Validator
	{
		/**
		 * A two-digit country code.
		 * 
		 * @default ""
		 */
    public var country:String = "";
		
		/**
		 * Default contructor.
		 */
		public function RoutingNumberValidator()
		{
			super();
		}		
    	
    /**
		 * Performs the actual validation routing number length based on the
		 * two-digit country code specified.
		 * 
		 * @param value the value that is to be validated
		 * 
		 * @return an empty Array if validation was successful, 
		 * 			otherwise an array of ValidationResult objects
		 */
  	override protected function doValidation( value:Object ):Array 
    {
  		var results:Array = super.doValidation( value );
  		
  		// if there are errors already, then exit
  		if( results.length > 0 ) 
      {
  			return results;
  		}
  		
  		var str:String = this.source[this.property];
  		
  		// if its empty, don't validate
  		if( StringUtils.isEmpty( str ) ) 
      {
  		  return results;
  		}
  		
  		var rule:RoutingCountryDefinition = RoutingNumberRules.getCountry( country );
  		var maxLength:int = ( rule == null )? 9: rule.length;
  		
  		if( str.length != maxLength ) 
      {
  			results.push( new ValidationResult (
  							true, 
  							null,
  							"badLength", 
  							resourceManager.getString("FlexCommon","ROUTING_NBR_BAD_LENGTH",[maxLength]) ) );
  		}
  		
  		return results;
  	}		
	}
}